package com.jframe.sys.controller.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.jframe.sso.model.CurUser;
import com.jframe.sys.controller.utils.SysConfig;


import javax.servlet.Filter;


public class LoginFilter implements Filter{
	protected  Log logger = LogFactory.getLog(getClass());

	private static String redirectUrl = null;

	private static String[] unFilterUri;
	
	public void init(FilterConfig filterConfig) throws ServletException {
		ServletContext servletContext = filterConfig.getServletContext();
		if(redirectUrl==null){
			redirectUrl = SysConfig.getRedirectUrl();
			unFilterUri = SysConfig.getUnFilterUrl().split("#");
		}
		//String license = (String) servletContext.getAttribute("license");
		//if(license==null||license.equals("false")){
		//	if(Yz.yz()){
				servletContext.setAttribute("license", "true");
		//	}else{
		//		servletContext.setAttribute("license", "false");
		//	}
		//}		
	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		String context = request.getContextPath() + "/";
		String uri = request.getRequestURI().replaceFirst(context, "");
		if (isFilter(uri)) {
			CurUser curUser = (CurUser) request.getSession().getAttribute("curUser");
			if (curUser == null ) {
				logger.info("用户未登录或超时,跳转到登录页面。。。");
				((HttpServletResponse) servletResponse).sendRedirect(request.getContextPath() + "/" + redirectUrl);
				return;
			}
		}
		filterChain.doFilter(servletRequest, servletResponse);
	}

	

	public void destroy() {

	}
	
	public boolean isFilter(String url) {
		//过滤空uri
		if (url == null || "".equals(url) ) {
			return false;
		} 
		else if (unFilterUri == null || unFilterUri.length == 0) {
			//指定不过滤URL为空，则全部过滤
			return true;
		} 
		else {
			//不过滤指定URL
			for (int i = 0; i < unFilterUri.length; i++) {
				if (url.equals(unFilterUri[i])) {
					return false;
				}else if(url.startsWith(unFilterUri[i]+"/")){
					return false;
				}
			}
			return true;
		}
	}

}
